//index.js
//获取应用实例
const app = getApp()
import { getScheduleList,getcategory,getMatchList } from '../../api/schedule.js'
import { getBannerList } from '../../api/banner.js'
import { removeObj } from '../../utils/removeObj.js'
import { hasLive } from '../../api/live.js'

Page({ 
  data: {
    hasLive:0,//赛事直播数量
    showToastState: false,//是否已加载全部
    duration: "500",
    current: 0,
    banner: [],
    lists:[],
    pageNum: 1,
    pageSize: 6,
    isRequst: false,//用来判断当前是否为请求状态
    requestNum:0, // 请求数 // 改请求数刷新会重置
    allRequestNum: 0 ,// 总请求数 // 该求数不重置，只在首次加载计数，用于是否显示showLoading
    category:[],
    activeTab: 0,
    isCurrent:{},//近期赛程
    isCurrentboxNoBg:'',
    total:'',
    imgDraw:{
      width: '144rpx',
      height: '144rpx',
      views: []
    },
    sharePath: '',
    visible:false
  },
  onLoad(){
    app._getSettingInfo(data => {
      this.setData({ settingInfo: data })
      let arr = [];
      let addArr = [data.miniCode, data.shareBg, data.shareBottomBg, data.shareTitle, data.shareTopModel]
      addArr.forEach((e, i) => {
        arr.push({ type: 'image', url: e, css: { top: '0', left: '0', width: '10rpx', height: '10rpx' } })
        if (i == addArr.length - 1) {
          this.setData({ ['imgDraw.views']: arr })
        }
      })
    })
  },
  onImgOK(e) {
    this.setData({ sharePath: e.detail.path, visible: true })
    //通知外部绘制完成，重置isCanDraw为false
    this.triggerEvent('initData');
  },
  onShow: function () {
    this.feach()
    this._getcategory()
    //获取近期赛程
    this._getisCurrent()
    //获取赛事直播数量
    this._hasLive()
  },
  _hasLive(){
    hasLive().then(res=>{
      this.setData({hasLive:res.data})
    })
  },
  // 去直播列表
  toLive(){
    wx.navigateTo({ url: '/pages/live_list/index' })
  },

  //获取近期赛程
  _getisCurrent(){
    getScheduleList({ isCurrent: 1, pageNum: 1, pageSize: 1 }).then(res => {
      if(res.rows.length>0){
        let day = app.timeFn(res.rows[0].timeStart, '-',false)
        res.rows[0].date = Number((day[4] ? '-' : '') + day[0])
        if(res.rows[0].image){//有图片
          res.rows[0].image=res.rows[0].image.split(',')
        } else {//没有图片
          app._getSettingInfo(data => {
            this.setData({ isCurrentboxNoBg: data.isCurrentboxNoBg })
          })
        }
        res.rows[0].shortAddress = res.rows[0].shortAddress.replace(/,/g, ' ')
        this.setData({ isCurrent: removeObj(res.rows[0], ['searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'remark', 'params', 'categoryName', 'userId', 'timeStart', 'timeEnd', 'time'])})
      }else{
        app._getSettingInfo(data => {
          this.setData({ isCurrentboxNoBg: data.isCurrentboxNoBg })
        })
      }
    })
  }, 
  //分类列表【4.13】
  _getcategory(){
    // let { category,activeTab } = this.data
    getcategory({recommendHome:1}).then(res => {
      let arr = []
      res.data.forEach(e=>{
        arr.push({ categoryId: e.categoryId, title:e.name})
      })
      this.setData({ category: arr})
      this._getMatchList()
    })
  },
  _getMatchList(){
    if (!this.data.isRequst) {
      this.setData({ isRequst:true})
      let { category, activeTab, pageNum, pageSize, lists } = this.data
      getMatchList({ categoryId: category[activeTab].categoryId, pageNum: pageNum, pageSize: pageSize, isRecommend: 1 }).then(res => {
        let arr = res.rows;
        arr = (pageNum == 1 ? arr : [...(pageNum == 1 ? [] : lists), ...arr])
        this.setData({ lists: arr, pageNum: pageNum + (arr.length > 0 ? 1 : 0), showToastState: lists.length < res.total, total: res.total, isRequst: false })
      })
    }
  },
  //列表数据重置
  changeData(e) {
    this.setData({ lists: e.detail })
  },
  //图片丢失时处理
  imgErr(e){
    let { banner} = this.data
    banner.splice(e.currentTarget.dataset.index, 1);
    this.setData({ banner: banner})
  },
  onTabCLick(e) {
    this.setData({ pageNum: 1,activeTab: e.currentTarget.dataset.index,isRequst:false})
    this._getMatchList()
  },
  onChange(e) {
    this.setData({ activeTab: e.currentTarget.dataset.index, isRequst: false })
  },
  feach() {
    this.setData({pageNum: 1, isRequst: false, requestNum: 0, showToastState:false })
    this._getBannerList()
  },
  //轮播图
  _getBannerList() {
    let { allRequestNum} = this.data
    if (allRequestNum<2){
      this.setData({ allRequestNum: allRequestNum+1})
    }
    getBannerList(allRequestNum < 2).then(res => {
      if (res.data.length > 0) {
        this.setData({ banner: removeObj(res.data, ['name','searchValue', 'createBy', 'createTime', 'updateBy', 'updateTime', 'remark', 'params', 'bannerId', 'sort', 'status'])})
      }
    })
  },
  getImgDetail(){
    let { current, banner} = this.data
    if (banner[current].page != null) {
      wx.navigateTo({
        url: '/' + banner[current].page,
      })
    }
  },
  swiperChange: function(e) {
    if (e.detail.source == 'touch' ||e.detail.source == 'autoplay') {
      this.setData({current: e.detail.current})
    }
  }, 
  changeSwiper(e){
    this.swiperChange({detail:{source:'touch',current: e.currentTarget.dataset.index}})
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // this.feach()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._getMatchList()
  },
  detailMothed(e){
    let d = e.currentTarget.dataset
    if(d.matchid==0){
        wx.navigateTo({
          url: "/pages/schedule_detail/index?id=" + d.id,
        })
    }else{
      wx.navigateTo({
        url: '/pages/competition_detail/index?id=' + d.matchid,
      })
    }
  }
})